package com.dragon.logical.service.auth.impl;

import com.alibaba.fastjson.JSONObject;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.UploadFileUtils;
import com.dragon.logical.service.auth.UploadFileService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.UUID;


@Service
public class UploadFileServiceImpl implements UploadFileService {
    /**
     * 域名
     */
    private final static String UPLOAD_URL = "http://pic.cqdragon.top";

    /**
     * access_key
     */
    private final  static String UPLOAD_ACCESS_KEY = "jX8nKFnaZFR7io75Y1f67mU28_hznlsC5t4Vlk20";

    /**
     * secret
     */
    private final static String UPLOAD_SECRET_KEY = "WrocoinzKsjZuRG6mO15A3rGDy34BfztuIc8fYCP";

    /**
     * bucket
     */
    private final static String UPLOAD_BUCKET = "dragon-system";

    Auth auth = Auth.create(UPLOAD_ACCESS_KEY,UPLOAD_SECRET_KEY);

    Configuration configuration = new Configuration(Zone.zone2());

    UploadManager uploadManager = new UploadManager(configuration);


    public String getUpToken() {
        return auth.uploadToken(UPLOAD_BUCKET);
    }

    @Override
    public HashMap<String, String> saveImage(MultipartFile file) throws IOException {
        HashMap<String, String> hashMap = new HashMap<>();
        String authToken = getUpToken();
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!UploadFileUtils.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, authToken);
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                hashMap.put("filePath",UPLOAD_URL + "/" + JSONObject.parseObject(res.bodyString()).get("key"));
                hashMap.put("fileName",file.getOriginalFilename());
                return hashMap;
            } else {
                throw new CustomException(ResultCode.ERROR.code(),"七牛异常:" + res.bodyString());
                //log.error("七牛异常:" + res.bodyString());
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            throw new CustomException(ResultCode.ERROR.code(),"七牛异常:" + e.getMessage());
        }
    }

    @Override
    public String saveLocalImage(MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();

        String path = "";

        try {
            byte[] bytes = file.getBytes();
            String localPath = System.getProperty("user.dir");
            File pfile = new File(localPath + "/fileupload/");
            if(!pfile.exists()){
                pfile.mkdir();
            }
            File file1 = new File(pfile,fileName);

            OutputStream outputStream = new FileOutputStream(file1);

            outputStream.write(bytes);

            path = file1.getAbsolutePath();
        }catch (IOException e){
            throw new CustomException(ResultCode.ERROR.code(),"上传文件失败:" + e.getMessage());
        }

        return path;
    }
}
